package controller

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"net/http"
	"strconv"
	"strings"

	platformController "gitee.com/wangshh_123/cross-pay-go/src/controller/platform"
	"gitee.com/wangshh_123/cross-pay-go/src/middleware"
	"gitee.com/wangshh_123/cross-pay-go/src/models"
	"gitee.com/wangshh_123/cross-pay-go/src/platform/providers/photonpay"
	photonmodels "gitee.com/wangshh_123/cross-pay-go/src/platform/providers/photonpay/models"
	photonpayServices "gitee.com/wangshh_123/cross-pay-go/src/platform/providers/photonpay/services"
	"gitee.com/wangshh_123/cross-pay-go/src/service"
	"gitee.com/wangshh_123/cross-pay-go/src/utils/auth"
	"gitee.com/wangshh_123/cross-pay-go/src/utils/common"
	commUtils "gitee.com/wangshh_123/cross-pay-go/src/utils/communication"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// UserController 用户控制器
type UserController struct {
	userService        *service.UserService
	db                 *gorm.DB
	photonPayClient    *photonpay.PhotonPayClient
	cardListController *platformController.CardListController
}

// NewUserController 创建用户控制器
func NewUserController(db *gorm.DB, photonPayClient *photonpay.PhotonPayClient, cardListController *platformController.CardListController) *UserController {
	return &UserController{
		userService:        service.NewUserService(),
		db:                 db,
		photonPayClient:    photonPayClient,
		cardListController: cardListController,
	}
}

// checkUserWritePermission 检查用户是否有user:write权限
func (c *UserController) checkUserWritePermission(ctx *gin.Context) bool {
	// 获取当前用户ID
	userID, exists := ctx.Get("user_id")
	if !exists {
		common.Error(ctx, http.StatusUnauthorized, "UNAUTHORIZED", nil)
		return false
	}

	// 检查用户是否有管理员权限和用户写入权限
	var role models.Role
	if err := c.db.Joins("JOIN user_roles ON user_roles.role_id = roles.id").
		Where("user_roles.user_id = ? AND roles.status = 1", userID).
		First(&role).Error; err != nil {
		common.Error(ctx, http.StatusForbidden, "NO_PERMISSION", err)
		return false
	}

	// 检查是否有管理员权限
	if role.Permissions == nil {
		role.Permissions = make(models.PermissionsMap)
	}
	if !role.Permissions["admin:access"] {
		common.Error(ctx, http.StatusForbidden, "NO_ADMIN_PERMISSION", nil)
		return false
	}

	// 检查是否有用户写入权限
	if !role.Permissions["user:write"] {
		common.Error(ctx, http.StatusForbidden, "NO_USER_WRITE_PERMISSION", nil)
		return false
	}

	return true
}

// Register 用户注册（宽松验证版本）
// @Summary 用户注册
// @Description 注册新用户（手机号可选）
// @Tags 用户管理
// @Accept json
// @Produce json
// @Param request body models.UserRegisterRequest true "注册信息"
// @Success 200 {object} models.UserRegisterResponse "注册成功"
// @Failure 400 {object} utils.Response "请求参数错误"
// @Failure 500 {object} utils.Response "服务器内部错误"
// @Router /api/v1/users/register [post]
func (c *UserController) Register(ctx *gin.Context) {
	var req struct {
		Username         string `json:"username" binding:"required,min=3,max=50"`
		Password         string `json:"password" binding:"required,min=6,max=20"`
		Email            string `json:"email" binding:"required,email,max=100"`
		Phone            string `json:"phone" binding:"omitempty"` // 手机号可选
		Name             string `json:"name" binding:"max=50"`
		VerificationCode string `json:"verification_code" binding:"required"`
		InvitationCode   string `json:"invitation_code" binding:"omitempty"`
	}

	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		return
	}

	// 创建邮件工具实例
	emailUtil, err := commUtils.NewEmailUtil()
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "create_email_util_failed", err)
		return
	}

	// 验证注册验证码
	valid, err := emailUtil.VerifyRegisterCode(req.Email, req.VerificationCode)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "verify_code_failed", err)
		return
	}
	if !valid {
		common.Error(ctx, http.StatusUnauthorized, "invalid_code", nil)
		return
	}

	// 注册用户
	user, err := c.userService.Register(
		req.Username,
		req.Password,
		req.Email,
		req.Phone,
		req.Name,
		req.InvitationCode,
	)
	if err != nil {
		// 国际化详细错误信息
		var detailCN, detailEN, detailVN string
		errMsg := err.Error()
		if strings.Contains(errMsg, "username already exists") {
			detailCN = "用户名已存在"
			detailEN = "Username already exists"
			detailVN = "Tên đăng nhập đã tồn tại"
		} else if strings.Contains(errMsg, "email already exists") {
			detailCN = "邮箱已存在"
			detailEN = "Email already exists"
			detailVN = "Email đã tồn tại"
		} else {
			detailCN = fmt.Sprintf("用户注册失败: %v", errMsg)
			detailEN = fmt.Sprintf("User registration failed: %v", errMsg)
			detailVN = fmt.Sprintf("Đăng ký người dùng thất bại: %v", errMsg)
		}
		common.Error(ctx, http.StatusInternalServerError, gin.H{
			"cn": detailCN,
			"en": detailEN,
			"vn": detailVN,
		}, errors.New(detailEN))
		return
	}

	common.Success(ctx, gin.H{
		"message": "user_register_success",
		"data":    user,
	})
}

// Login 用户登录
// @Summary 用户登录
// @Description 用户登录接口
// @Tags 用户管理
// @Accept json
// @Produce json
// @Param request body models.UserLoginRequest true "登录信息"
// @Success 200 {object} models.UserLoginResponse "登录成功"
// @Failure 400 {object} utils.Response "请求参数错误"
// @Failure 401 {object} utils.Response "用户名或密码错误"
// @Failure 500 {object} utils.Response "服务器内部错误"
// @Router /api/v1/users/login [post]
func (c *UserController) Login(ctx *gin.Context) {
	var req struct {
		LoginId          string `json:"login_id" binding:"required"`
		Password         string `json:"password" binding:"required"`
		VerificationCode string `json:"verification_code" binding:"required"`
		AuthMethod       string `json:"auth_method" binding:"required,oneof=email sms ga"`
	}

	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		return
	}

	// 验证用户名和密码
	user, err := c.userService.Login(req.LoginId, req.Password)
	if err != nil {
		common.Error(ctx, http.StatusUnauthorized, "invalid_credentials", err)
		return
	}

	// 获取用户的认证方式
	authMethods, err := c.userService.GetUserAuthMethods(int64(user.ID))
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "get_auth_methods_failed", err)
		return
	}

	// 验证认证方式
	var authMethod *models.UserAuthMethod
	for _, method := range authMethods {
		if method.AuthType == req.AuthMethod && method.IsEnabled == 1 {
			authMethod = &method
			break
		}
	}

	if authMethod == nil {
		common.Error(ctx, http.StatusForbidden, "auth_method_not_enabled", nil)
		return
	}

	// 根据认证方式验证验证码
	var isValid bool
	switch req.AuthMethod {
	case "email":
		emailUtil, err := commUtils.NewEmailUtil()
		if err != nil {
			common.Error(ctx, http.StatusInternalServerError, "create_email_util_failed", err)
			return
		}
		isValid, err = emailUtil.VerifyLoginCode(user.Email, req.VerificationCode)
	case "sms":
		smsUtil, err := commUtils.NewSmsUtil()
		if err != nil {
			common.Error(ctx, http.StatusInternalServerError, "create_sms_util_failed", err)
			return
		}
		isValid, err = smsUtil.VerifyCode(user.Phone, req.VerificationCode, "login")
	case "ga":
		gaUtil := auth.NewGAUtil()
		isValid = gaUtil.VerifyToken(authMethod.AuthSecret, req.VerificationCode)
		err = nil
	default:
		common.Error(ctx, http.StatusBadRequest, "unsupported_auth_method", nil)
		return
	}

	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "verify_code_failed", err)
		return
	}

	if !isValid {
		common.Error(ctx, http.StatusUnauthorized, "invalid_code", nil)
		return
	}

	// 生成JWT令牌
	token, err := auth.GenerateToken(int64(user.ID), user.Username, user.RoleID)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "user_login_failed", err)
		return
	}

	// 返回用户信息和令牌
	common.Success(ctx, models.UserLoginResponse{
		Token: token,
		User: models.UserInfo{
			ID:        int64(user.ID),
			Username:  user.Username,
			Email:     user.Email,
			Phone:     user.Phone,
			RoleID:    user.RoleID,
			Status:    int(user.Status),
			CreatedAt: user.CreatedAt,
		},
	})
}

// Logout 用户登出
func (c *UserController) Logout(ctx *gin.Context) {
	common.Success(ctx, gin.H{
		"message": "user_logout_success",
	})
}

// GetProfile 获取用户资料
// @Summary 获取用户个人资料
// @Description 获取当前登录用户的个人资料信息
// @Tags 用户管理
// @Accept json
// @Produce json
// @Security ApiKeyAuth
// @Success 200 {object} models.UserProfileResponse "成功获取用户资料"
// @Failure 401 {object} utils.Response "未授权"
// @Failure 500 {object} utils.Response "服务器内部错误"
// @Router /api/v1/users/profile [get]
func (c *UserController) GetProfile(ctx *gin.Context) {
	// 从上下文中获取用户ID，并进行类型断言检查
	userID, exists := ctx.Get("user_id")
	if !exists {
		common.Error(ctx, http.StatusUnauthorized, "unauthorized", errors.New("user not authenticated"))
		return
	}

	// 类型断言检查
	id, ok := userID.(int64)
	if !ok {
		common.Error(ctx, http.StatusInternalServerError, "invalid_user_id", errors.New("invalid user ID type"))
		return
	}

	profile, err := c.userService.GetUserProfileWithRole(id)
	if err != nil {
		common.Error(ctx, http.StatusNotFound, "user_not_found", err)
		return
	}

	common.Success(ctx, profile)
}

// UpdateProfile 更新用户资料
func (c *UserController) UpdateProfile(ctx *gin.Context) {
	userIDVal, exists := ctx.Get("user_id")
	if !exists {
		common.Error(ctx, http.StatusUnauthorized, "user_not_found", nil)
		return
	}
	var userID int64
	if v, ok := userIDVal.(int64); ok {
		userID = v
	} else if v, ok := userIDVal.(float64); ok {
		userID = int64(v)
	} else {
		common.Error(ctx, http.StatusUnauthorized, "user_not_found", nil)
		return
	}
	var req struct {
		Email string `json:"email" binding:"omitempty,email"`
		Phone string `json:"phone" binding:"omitempty"`
		Name  string `json:"name" binding:"omitempty,max=50"`
	}

	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		return
	}

	// 获取用户当前信息
	var currentUser models.User
	if err := c.db.First(&currentUser, userID).Error; err != nil {
		common.Error(ctx, http.StatusInternalServerError, "get_user_failed", err)
		return
	}

	updatedUser, err := c.userService.UpdateUser(userID, req.Email, req.Phone, req.Name, currentUser.RoleID, currentUser.Status)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "user_profile_update_failed", err)
		return
	}

	common.Success(ctx, gin.H{
		"message": "user_profile_update_success",
		"data":    updatedUser,
	})
}

// ChangePassword 修改密码
func (c *UserController) ChangePassword(ctx *gin.Context) {
	var req struct {
		CurrentPassword string `json:"current_password" binding:"required"`
		NewPassword     string `json:"new_password" binding:"required,min=8"`
	}

	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		return
	}

	// 验证密码格式
	hasLetter := false
	hasNumber := false
	hasSpecial := false
	for _, char := range req.NewPassword {
		switch {
		case (char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z'):
			hasLetter = true
		case char >= '0' && char <= '9':
			hasNumber = true
		case char == '@' || char == '$' || char == '!' || char == '%' || char == '*' || char == '#' || char == '?' || char == '&':
			hasSpecial = true
		}
	}

	if !hasLetter || !hasNumber || !hasSpecial {
		common.Error(ctx, http.StatusBadRequest, "invalid_password_format", nil)
		return
	}

	// 从上下文中获取用户ID
	userID := ctx.GetInt64("user_id")

	if err := c.userService.ChangePassword(userID, req.CurrentPassword, req.NewPassword); err != nil {
		common.Error(ctx, http.StatusBadRequest, "password_change_failed", err)
		return
	}

	common.Success(ctx, gin.H{
		"message": "password_change_success",
	})
}

// ListUsers 获取用户列表（管理员）
func (c *UserController) ListUsers(ctx *gin.Context) {
	// 获取分页参数
	pageIndex, pageSize := common.GetPaginationParams(ctx)
	page := int(pageIndex)
	pageSizeInt := int(pageSize)
	// 获取搜索关键字
	keyword := ctx.Query("keyword")
	// 获取部门ID筛选条件
	departmentIDStr := ctx.Query("department_id")
	var departmentID *int64
	if departmentIDStr != "" {
		if id, err := strconv.ParseInt(departmentIDStr, 10, 64); err == nil {
			departmentID = &id
		}
	}

	// 获取排序参数
	sortBy := ctx.Query("sort_by")
	sortOrder := ctx.Query("sort_order")

	// 获取用户列表
	users, total, err := c.userService.ListUsers(page, pageSizeInt, keyword, departmentID, sortBy, sortOrder)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "error", err)
		return
	}

	// 获取所有用户的 Matrix 账户信息
	var userIDs []int64
	for _, user := range users {
		userIDs = append(userIDs, int64(user.ID))
	}
	// 查询用户角色信息
	type UserRole struct {
		UserID    int64  `gorm:"column:user_id"`
		RoleID    int64  `gorm:"column:role_id"`
		RoleName  string `gorm:"column:name"`
		Status    int8   `gorm:"column:status"`
		CreatedAt string `gorm:"column:created_at"`
	}
	var userRoles []UserRole
	if err := c.db.Table("user_roles").
		Select("user_roles.user_id, user_roles.role_id, roles.name, roles.status, user_roles.created_at").
		Joins("JOIN roles ON user_roles.role_id = roles.id").
		Where("user_roles.user_id IN ? AND roles.status = 1", userIDs).
		Find(&userRoles).Error; err != nil {
		common.Error(ctx, http.StatusInternalServerError, "get_user_roles_failed", err)
		return
	}

	// 构建用户ID到角色信息的映射
	userRoleMap := make(map[int64][]UserRole)
	for _, ur := range userRoles {
		userRoleMap[ur.UserID] = append(userRoleMap[ur.UserID], ur)
	}

	// 查询所有用户的矩阵账户信息
	type MatrixAccount struct {
		ID                    int64  `gorm:"column:id"`
		UserID                int64  `gorm:"column:user_id"`
		MatrixAccount         string `gorm:"column:matrix_account"`
		MatrixAccountName     string `gorm:"column:matrix_account_name"`
		ParentMatrixAccountID *int64 `gorm:"column:parent_matrix_account_id"`
		Status                string `gorm:"column:status"`
	}
	var matrixAccounts []MatrixAccount
	if err := c.db.Table("user_matrix_accounts").
		Select("id, user_id, matrix_account, matrix_account_name, parent_matrix_account_id, status").
		Where("user_id IN ? AND status = ?", userIDs, "active").
		Find(&matrixAccounts).Error; err != nil {
		common.Error(ctx, http.StatusInternalServerError, "get_matrix_accounts_failed", err)
		return
	}

	// 构建用户ID到矩阵账户的映射
	matrixAccountMap := make(map[int64]MatrixAccount)
	for _, account := range matrixAccounts {
		matrixAccountMap[account.UserID] = account
	}

	// 获取所有父级矩阵账户ID
	var parentMatrixAccountIDs []int64
	for _, account := range matrixAccounts {
		if account.ParentMatrixAccountID != nil {
			parentMatrixAccountIDs = append(parentMatrixAccountIDs, *account.ParentMatrixAccountID)
		}
	}

	// 查询父级矩阵账户信息
	var parentMatrixAccounts []MatrixAccount
	if len(parentMatrixAccountIDs) > 0 {
		if err := c.db.Table("user_matrix_accounts").
			Select("id, user_id, matrix_account, matrix_account_name, parent_matrix_account_id, status").
			Where("id IN ?", parentMatrixAccountIDs).
			Find(&parentMatrixAccounts).Error; err != nil {
			common.Error(ctx, http.StatusInternalServerError, "get_parent_matrix_accounts_failed", err)
			return
		}
	}

	// 构建父级矩阵账户ID到账户信息的映射
	parentMatrixAccountMap := make(map[int64]MatrixAccount)
	for _, account := range parentMatrixAccounts {
		parentMatrixAccountMap[account.ID] = account
	}

	// 查询用户部门信息
	type UserDepartment struct {
		UserID         int64  `gorm:"column:user_id"`
		DepartmentID   int64  `gorm:"column:department_id"`
		DepartmentName string `gorm:"column:name"`
		DepartmentCode string `gorm:"column:code"`
		JoinDate       string `gorm:"column:join_date"`
		Status         string `gorm:"column:status"`
	}
	var userDepartments []UserDepartment
	if err := c.db.Table("department_users").
		Select("department_users.user_id, department_users.department_id, departments.name, departments.code, department_users.join_date, department_users.status").
		Joins("JOIN departments ON department_users.department_id = departments.id").
		Where("department_users.user_id IN ? AND department_users.status = ?", userIDs, "active").
		Find(&userDepartments).Error; err != nil {
		common.Error(ctx, http.StatusInternalServerError, "get_user_departments_failed", err)
		return
	}

	// 构建用户ID到部门信息的映射
	userDepartmentMap := make(map[int64]UserDepartment)
	for _, ud := range userDepartments {
		userDepartmentMap[ud.UserID] = ud
	}

	// 将Matrix账户信息和角色信息添加到用户信息中
	type UserWithMatrixAndRoles struct {
		models.User
		MatrixAccount     string     `json:"matrix_account"`
		MatrixAccountName string     `json:"matrix_account_name"`
		Roles             []UserRole `json:"roles"`
		Department        *struct {
			ID       int64  `json:"id"`
			Name     string `json:"name"`
			Code     string `json:"code"`
			JoinDate string `json:"join_date"`
		} `json:"department,omitempty"`
		ParentMatrixAccount *struct {
			MatrixAccount     string `json:"matrix_account"`
			MatrixAccountName string `json:"matrix_account_name"`
		} `json:"parent_matrix_account,omitempty"`
	}

	var usersWithMatrixAndRoles []UserWithMatrixAndRoles
	for _, user := range users {
		userWithMatrixAndRoles := UserWithMatrixAndRoles{
			User:  user,
			Roles: userRoleMap[int64(user.ID)],
		}

		// 添加矩阵账户信息
		if matrixAccount, exists := matrixAccountMap[int64(user.ID)]; exists {
			userWithMatrixAndRoles.MatrixAccount = matrixAccount.MatrixAccount
			userWithMatrixAndRoles.MatrixAccountName = matrixAccount.MatrixAccountName

			// 检查用户是否有 sub_user 角色
			hasSubUserRole := false
			for _, role := range userRoleMap[int64(user.ID)] {
				if role.RoleName == "sub_user" {
					hasSubUserRole = true
					break
				}
			}

			// 如果是 sub_user 且有父级矩阵账户，添加父级矩阵账户信息
			if hasSubUserRole && matrixAccount.ParentMatrixAccountID != nil {
				if parentAccount, exists := parentMatrixAccountMap[*matrixAccount.ParentMatrixAccountID]; exists {
					userWithMatrixAndRoles.ParentMatrixAccount = &struct {
						MatrixAccount     string `json:"matrix_account"`
						MatrixAccountName string `json:"matrix_account_name"`
					}{
						MatrixAccount:     parentAccount.MatrixAccount,
						MatrixAccountName: parentAccount.MatrixAccountName,
					}
				}
			}
		}

		// 添加部门信息
		if department, exists := userDepartmentMap[int64(user.ID)]; exists {
			userWithMatrixAndRoles.Department = &struct {
				ID       int64  `json:"id"`
				Name     string `json:"name"`
				Code     string `json:"code"`
				JoinDate string `json:"join_date"`
			}{
				ID:       department.DepartmentID,
				Name:     department.DepartmentName,
				Code:     department.DepartmentCode,
				JoinDate: department.JoinDate,
			}
		}

		usersWithMatrixAndRoles = append(usersWithMatrixAndRoles, userWithMatrixAndRoles)
	}

	// 返回分页信息
	common.Success(ctx, gin.H{
		"data": usersWithMatrixAndRoles,
		"pagination": gin.H{
			"pageIndex": pageIndex,
			"pageSize":  pageSize,
			"total":     total,
		},
	})
}

// GetUser 获取指定用户信息（管理员）
func (c *UserController) GetUser(ctx *gin.Context) {
	id, err := strconv.ParseInt(ctx.Param("id"), 10, 64)
	if err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		return
	}

	user, err := c.userService.GetUserByID(id)
	if err != nil {
		common.Error(ctx, http.StatusNotFound, "user_not_found", err)
		return
	}

	common.Success(ctx, user)
}

// UpdateUser 更新指定用户信息（管理员）
func (c *UserController) UpdateUser(ctx *gin.Context) {
	if !c.checkUserWritePermission(ctx) {
		return
	}

	id, err := strconv.ParseInt(ctx.Param("id"), 10, 64)
	if err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		return
	}

	// 获取当前用户信息
	var currentUser models.User
	if err := c.db.First(&currentUser, id).Error; err != nil {
		common.Error(ctx, http.StatusNotFound, "user_not_found", err)
		return
	}

	// 读取请求体
	body, err := ctx.GetRawData()
	if err != nil {
		log.Printf("读取请求体失败: %v", err)
		common.Error(ctx, http.StatusBadRequest, "invalid_request", err)
		return
	}

	// 如果请求体为空，返回错误
	if len(body) == 0 {
		common.Error(ctx, http.StatusBadRequest, "empty_request", errors.New("请求体不能为空"))
		return
	}

	// 解析JSON
	var req map[string]interface{}
	if err := json.Unmarshal(body, &req); err != nil {
		log.Printf("JSON解析错误: %v, 请求体: %s", err, string(body))
		common.Error(ctx, http.StatusBadRequest, "invalid_json", err)
		return
	}

	// 准备更新参数
	email := currentUser.Email
	phone := currentUser.Phone
	name := currentUser.Name
	roleID := currentUser.RoleID
	status := currentUser.Status

	// 更新邮箱
	if v, ok := req["email"].(string); ok && v != "" {
		email = v
	}
	// 更新手机号
	if v, ok := req["phone"].(string); ok && v != "" {
		phone = v
	}
	// 更新姓名
	if v, ok := req["name"].(string); ok && v != "" {
		name = v
	}
	// 更新角色
	if v, ok := req["role"].(string); ok && v != "" {
		var role models.Role
		if err := c.db.Where("name = ?", v).First(&role).Error; err != nil {
			common.Error(ctx, http.StatusBadRequest, "invalid_role", err)
			return
		}
		roleID = role.ID
	}

	// 更新状态
	if v, ok := req["status"].(float64); ok {
		status = int8(v)
	}

	// 记录更新参数
	log.Printf("更新用户参数: id=%d, email=%s, phone=%s, name=%s, roleID=%d, status=%d",
		id, email, phone, name, roleID, status)

	user, err := c.userService.UpdateUser(id, email, phone, name, roleID, status)
	if err != nil {
		log.Printf("更新用户失败: %v", err)
		common.Error(ctx, http.StatusInternalServerError, "user_profile_update_failed", err)
		return
	}

	common.Success(ctx, gin.H{
		"message": "user_profile_update_success",
		"data":    user,
	})
}

// DeleteUser 删除用户（管理员）
func (c *UserController) DeleteUser(ctx *gin.Context) {
	id, err := strconv.ParseInt(ctx.Param("id"), 10, 64)
	if err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		return
	}

	err = c.userService.DeleteUser(id)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "error", err)
		return
	}

	common.Success(ctx, gin.H{
		"message": "success",
	})
}

// GetUserAuthMethods 获取用户的认证方式
func (c *UserController) GetUserAuthMethods(ctx *gin.Context) {
	userID := ctx.GetInt64("user_id")

	methods, err := c.userService.GetUserAuthMethods(userID)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "get_auth_methods_failed", err)
		return
	}

	common.Success(ctx, gin.H{
		"methods": methods,
	})
}

// GetUserLoginRecords 获取用户最近的登录记录
func (c *UserController) GetUserLoginRecords(ctx *gin.Context) {
	userID := ctx.GetInt64("user_id")

	record, err := c.userService.GetLastLoginRecord(userID)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "get_login_records_failed", err)
		return
	}

	common.Success(ctx, gin.H{
		"record": record,
	})
}

// UpdateUserAuthMethod 更新用户认证方式
func (c *UserController) UpdateUserAuthMethod(ctx *gin.Context) {
	var req struct {
		AuthType   string `json:"auth_type" binding:"required"`
		AuthSecret string `json:"auth_secret"`
		AuthConfig string `json:"auth_config"`
		IsEnabled  int8   `json:"is_enabled" binding:"required"`
		Priority   int8   `json:"priority"`
	}

	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		return
	}

	userID := ctx.GetInt64("user_id")

	method := &models.UserAuthMethod{
		UserID:     userID,
		AuthType:   req.AuthType,
		AuthSecret: req.AuthSecret,
		AuthConfig: req.AuthConfig,
		IsEnabled:  req.IsEnabled,
		Priority:   req.Priority,
	}

	if err := c.userService.UpdateUserAuthMethod(method); err != nil {
		common.Error(ctx, http.StatusInternalServerError, "auth_method_update_failed", err)
		return
	}

	common.Success(ctx, gin.H{
		"message": "auth_method_update_success",
		"method":  method,
	})
}

// CreateUserAuthMethod 创建或更新用户认证方式
func (c *UserController) CreateUserAuthMethod(ctx *gin.Context) {
	var req struct {
		AuthType   string `json:"auth_type" binding:"required,oneof=email sms ga totp"`
		AuthSecret string `json:"auth_secret" binding:"omitempty,max=100"`
		AuthConfig string `json:"auth_config" binding:"omitempty,json"`
		IsEnabled  int8   `json:"is_enabled" binding:"oneof=0 1"`
		Priority   int8   `json:"priority" binding:"omitempty,min=0"`
	}

	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		return
	}

	// 从上下文中获取用户ID
	userIDVal, exists := ctx.Get("user_id")
	if !exists {
		common.Error(ctx, http.StatusUnauthorized, "unauthorized", nil)
		return
	}

	// 类型断言检查
	userID, ok := userIDVal.(int64)
	if !ok {
		common.Error(ctx, http.StatusInternalServerError, "invalid_user_id", errors.New("invalid user ID type"))
		return
	}

	// 验证用户是否存在
	if _, err := c.userService.GetUserByID(userID); err != nil {
		common.Error(ctx, http.StatusNotFound, "user_not_found", err)
		return
	}

	// 检查认证方式是否已存在
	exists, err := c.userService.CheckAuthMethodExists(userID, req.AuthType)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "auth_method_check_failed", err)
		return
	}

	if exists {
		// 获取现有的认证方式
		existingMethod, err := c.userService.GetUserAuthMethod(userID, req.AuthType)
		if err != nil {
			common.Error(ctx, http.StatusInternalServerError, "get_auth_method_failed", err)
			return
		}

		// 更新现有认证方式的字段
		existingMethod.AuthSecret = req.AuthSecret
		existingMethod.AuthConfig = req.AuthConfig
		existingMethod.IsEnabled = req.IsEnabled
		existingMethod.Priority = req.Priority

		// 更新认证方式
		if err := c.userService.UpdateUserAuthMethod(existingMethod); err != nil {
			common.Error(ctx, http.StatusInternalServerError, "auth_method_update_failed", err)
			return
		}

		common.Success(ctx, gin.H{
			"message": "auth_method_update_success",
			"method":  existingMethod,
		})
	} else {
		// 创建新的认证方式
		method := &models.UserAuthMethod{
			UserID:     userID,
			AuthType:   req.AuthType,
			AuthSecret: req.AuthSecret,
			AuthConfig: req.AuthConfig,
			IsEnabled:  req.IsEnabled,
			Priority:   req.Priority,
		}

		if err := c.userService.CreateUserAuthMethod(method); err != nil {
			common.Error(ctx, http.StatusInternalServerError, "auth_method_create_failed", err)
			return
		}

		common.Success(ctx, gin.H{
			"message": "auth_method_create_success",
			"method":  method,
		})
	}
}

// SendForgotPasswordEmailCode 发送忘记密码邮箱验证码
func (c *UserController) SendForgotPasswordEmailCode(ctx *gin.Context) {
	var req struct {
		Email string `json:"email" binding:"required,email"`
	}

	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		return
	}

	if err := c.userService.SendForgotPasswordEmailCode(req.Email); err != nil {
		common.Error(ctx, http.StatusInternalServerError, "verification_code_send_failed", err)
		return
	}

	common.Success(ctx, gin.H{
		"message": "verification_code_sent",
	})
}

// SendForgotPasswordSmsCode 发送忘记密码短信验证码
func (c *UserController) SendForgotPasswordSmsCode(ctx *gin.Context) {
	var req struct {
		Phone string `json:"phone" binding:"required,len=11"`
	}

	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		return
	}

	if err := c.userService.SendForgotPasswordSmsCode(req.Phone); err != nil {
		common.Error(ctx, http.StatusInternalServerError, "verification_code_send_failed", err)
		return
	}

	common.Success(ctx, gin.H{
		"message": "verification_code_sent",
	})
}

// ResetPassword 重置密码
func (c *UserController) ResetPassword(ctx *gin.Context) {
	var req struct {
		Email            string `json:"email" binding:"omitempty,email"`
		Phone            string `json:"phone" binding:"omitempty,len=11"`
		VerificationCode string `json:"verification_code" binding:"required"`
		NewPassword      string `json:"new_password" binding:"required,min=8"`
	}

	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		return
	}

	if err := c.userService.ForgotPassword(req.Email, req.Phone, req.VerificationCode, req.NewPassword); err != nil {
		switch err.Error() {
		case "missing_required_params":
			common.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		case "password_too_short":
			common.Error(ctx, http.StatusBadRequest, "invalid_password_format", err)
		case "password_missing_letter":
			common.Error(ctx, http.StatusBadRequest, "invalid_password_format", err)
		case "password_missing_number":
			common.Error(ctx, http.StatusBadRequest, "invalid_password_format", err)
		case "password_missing_special":
			common.Error(ctx, http.StatusBadRequest, "invalid_password_format", err)
		case "user_not_found":
			common.Error(ctx, http.StatusNotFound, "user_not_found", err)
		default:
			common.Error(ctx, http.StatusInternalServerError, "password_reset_failed", err)
		}
		return
	}

	common.Success(ctx, gin.H{
		"message": "password_reset_success",
	})
}

// SendVerificationCode 发送验证码
// @Summary 发送邮箱验证码
// @Description 发送邮箱验证码用于注册
// @Tags 用户管理
// @Accept json
// @Produce json
// @Param request body models.SendVerificationCodeRequest true "发送验证码请求"
// @Success 200 {object} utils.Response "验证码发送成功"
// @Failure 400 {object} utils.Response "请求参数错误"
// @Failure 500 {object} utils.Response "服务器内部错误"
// @Router /api/v1/auth/send-register-code [post]
func (c *UserController) SendVerificationCode(ctx *gin.Context) {
	var req struct {
		Email string `json:"email" binding:"required,email"`
	}

	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		return
	}

	// 检查邮箱是否已被注册
	_, err := c.userService.FindByLoginID(req.Email)
	if err == nil {
		common.Error(ctx, http.StatusBadRequest, "email_already_exists", nil)
		return
	}

	// 创建邮件工具实例
	emailUtil, err := commUtils.NewEmailUtil()
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "create_email_util_failed", err)
		return
	}

	// 发送验证码
	if err := emailUtil.SendVerificationCode(req.Email, "register"); err != nil {
		common.Error(ctx, http.StatusInternalServerError, "send_verification_code_failed", err)
		return
	}

	common.Success(ctx, gin.H{
		"message": "verification_code_sent",
	})
}

// GetUserInfo 获取用户详细信息
// @Summary 获取用户详细信息
// @Description 获取指定用户的详细信息，包括基本信息、Matrix账户信息和卡片统计信息
// @Tags 用户管理
// @Accept json
// @Produce json
// @Security ApiKeyAuth
// @Param id path int true "用户ID"
// @Success 200 {object} models.UserInfoResponse "成功获取用户信息"
// @Failure 401 {object} utils.Response "未授权"
// @Failure 403 {object} utils.Response "无权限"
// @Failure 404 {object} utils.Response "用户不存在"
// @Failure 500 {object} utils.Response "服务器内部错误"
// @Router /api/v1/users/{id}/info [get]
func (c *UserController) GetUserInfo(ctx *gin.Context) {
	// 获取要查询的用户ID
	targetID, err := strconv.ParseInt(ctx.Param("id"), 10, 64)
	if err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_user_id", err)
		return
	}

	// 获取用户基本信息
	user, err := c.userService.GetUserByID(targetID)
	if err != nil {
		common.Error(ctx, http.StatusNotFound, "user_not_found", err)
		return
	}

	// 查询汇率损失率（ExchangeLossRate）
	exchangeLossRate := "2.00" // 默认值
	type ExchangeLossRule struct {
		Rate string `gorm:"column:rate"`
	}
	var rule ExchangeLossRule
	err = c.db.Table("exchange_loss_rules").
		Select("rate").
		Where("user_id = ? AND status = ?", targetID, "active").
		First(&rule).Error
	if err == nil {
		exchangeLossRate = rule.Rate
	} else {
		// 查找全局默认规则
		err = c.db.Table("exchange_loss_rules").
			Select("rate").
			Where("user_id IS NULL AND status = ? AND is_default = 1", "active").
			First(&rule).Error
		if err == nil {
			exchangeLossRate = rule.Rate
		}
	}

	// 获取用户的 Matrix 账户信息
	matrixAccount, err := c.userService.GetUserMatrixAccount(targetID)
	if err != nil {
		if err != gorm.ErrRecordNotFound {
			common.Error(ctx, http.StatusInternalServerError, "get_matrix_account_failed", err)
			return
		}
	}

	// 获取用户角色信息
	var userRole models.UserRole
	var roleID int64 = 2 // 默认角色ID
	if err := c.db.Where("user_id = ?", targetID).First(&userRole).Error; err == nil {
		roleID = userRole.RoleID
	}

	// 根据角色和平台类型获取正确的余额
	var balance string = "0.00"
	if matrixAccount.MatrixAccount != "" {
		switch roleID {
		case 2: // 普通用户
			if matrixAccount.PlatformType == "hlpay" {
				// 从 hlpay_account_balances 表获取余额
				var hlpayBalance models.HlPayAccountBalance
				if err := c.db.Where("owner_no = ? AND status = 'active'", matrixAccount.MatrixAccount).First(&hlpayBalance).Error; err == nil {
					balance = hlpayBalance.RealTimeBalance.String()
				}
			} else if matrixAccount.PlatformType == "photonpay" {
				// 调用光子接口获取余额
				params := photonmodels.AccountListQueryParams{
					MatrixAccount: matrixAccount.MatrixAccount,
				}
				if accountListResp, err := photonpayServices.GetAccountList(context.Background(), c.photonPayClient, params); err == nil && len(accountListResp.Data) > 0 {
					// 取第一个账户的余额
					balance = fmt.Sprintf("%.2f", accountListResp.Data[0].RealTimeBalance)
				}
			}
		case 3: // 主账号 - 从 master_accounts 表获取余额
			var masterAccount models.MasterAccount
			if err := c.db.Where("user_id = ?", targetID).First(&masterAccount).Error; err == nil {
				balance = masterAccount.Balance.String()
			}
		case 5: // 子账号 - 从 sub_accounts 表获取余额
			var subAccount models.SubAccount
			if err := c.db.Where("user_id = ?", targetID).First(&subAccount).Error; err == nil {
				balance = subAccount.Balance.String()
			}
		default:
			// 其他角色使用默认余额
			balance = "0.00"
		}
	}

	// 构建用户信息响应
	userInfo := models.UserInfoResponse{
		ID:               int64(user.ID),
		Username:         user.Username,
		Email:            user.Email,
		Phone:            user.Phone,
		Status:           user.Status,
		LastLoginTime:    &user.LastLoginTime,
		ExchangeLossRate: exchangeLossRate,
	}

	// 统计卡片信息（只做统计，不返回完整卡片列表）
	cardStats := gin.H{
		"totalCards":      0,
		"frozenCards":     0,
		"cancelledCards":  0,
		"totalBalance":    "0.00",
		"cardTypeStats":   map[string]int{},
		"cardStatusStats": map[string]int{},
		"platform":        matrixAccount.PlatformType,
		"note":            "使用聚合控制器获取卡列表",
	}
	if matrixAccount.MatrixAccount != "" {
		// 设置平台信息到上下文中，供 CardListController 使用
		platformInfo := &middleware.PlatformInfo{
			PlatformType:  matrixAccount.PlatformType,
			MatrixAccount: matrixAccount.MatrixAccount,
			Status:        matrixAccount.Status,
		}
		ctx.Set("platform_info", platformInfo)
		ctx.Set("matrix_account_info", &matrixAccount)

		// 设置用户信息到上下文中
		claims := &auth.Claims{
			UserID: targetID,
			RoleID: 1, // 管理员角色，确保有权限查看所有卡
		}
		ctx.Set("claims", claims)

		// 获取卡片统计信息（只做统计，不返回完整卡片列表）
		// 这里直接调用 CardListController 的内部统计方法
		if matrixAccount.PlatformType == "photonpay" {
			params := photonmodels.CardListQueryParams{
				MatrixAccount: matrixAccount.MatrixAccount,
				PageSize:      1000,
			}
			cardListResp, err := photonpayServices.GetCardList(context.Background(), c.photonPayClient, params)
			if err == nil {
				cardList := cardListResp.Data
				totalCards := len(cardList)
				frozenCards := 0
				cancelledCards := 0
				totalBalance := 0.0
				cardStatusStats := make(map[string]int)
				cardTypeStats := make(map[string]int)
				for _, card := range cardList {
					totalBalance += card.CardBalance
					cardStatusStats[card.CardStatus]++
					cardTypeStats[card.CardType]++
					if card.CardStatus == "frozen" {
						frozenCards++
					}
					if card.CardStatus == "cancelled" || card.CardStatus == "closed" {
						cancelledCards++
					}
				}
				cardStats = gin.H{
					"totalCards":      totalCards,
					"frozenCards":     frozenCards,
					"cancelledCards":  cancelledCards,
					"totalBalance":    fmt.Sprintf("%.2f", totalBalance),
					"cardTypeStats":   cardTypeStats,
					"cardStatusStats": cardStatusStats,
					"platform":        matrixAccount.PlatformType,
					"note":            "使用聚合控制器获取卡列表",
				}
			}
		} else if matrixAccount.PlatformType == "hlpay" {
			// 对于 HlPay，我们直接使用数据库中的用户卡信息进行统计
			var userCards []models.UserCard
			if err := c.db.Where("user_id = ? AND platform = ?", targetID, "hlPay").Find(&userCards).Error; err == nil {
				totalCards := len(userCards)
				frozenCards := 0
				cancelledCards := 0
				totalBalance := 0.0
				cardStatusStats := make(map[string]int)
				cardTypeStats := make(map[string]int)

				for _, userCard := range userCards {
					balance := userCard.TotalTransferAmount.InexactFloat64()
					totalBalance += balance
					cardStatusStats["NORMAL"]++ // 默认状态
					cardTypeStats["recharge"]++ // HlPay默认常规卡
				}

				cardStats = gin.H{
					"totalCards":      totalCards,
					"frozenCards":     frozenCards,
					"cancelledCards":  cancelledCards,
					"totalBalance":    fmt.Sprintf("%.2f", totalBalance),
					"cardTypeStats":   cardTypeStats,
					"cardStatusStats": cardStatusStats,
					"platform":        matrixAccount.PlatformType,
					"note":            "使用聚合控制器获取卡列表",
				}
			}
		}
	}

	common.Success(ctx, gin.H{
		"data": gin.H{
			"userInfo": userInfo,
			"matrixAccount": gin.H{
				"id":                  matrixAccount.ID,
				"matrixAccount":       matrixAccount.MatrixAccount,
				"matrixAccountName":   matrixAccount.MatrixAccountName,
				"status":              matrixAccount.Status,
				"createdAt":           matrixAccount.CreatedAt,
				"balance":             balance,
				"totalTransferAmount": matrixAccount.TotalTransferAmount,
			},
			"cardStats": cardStats,
		},
	})
}
